package com.zeta.demo.mq.common.consumer;

import cn.hutool.core.bean.BeanUtil;
import com.zeta.api.model.DemoDTO;
import com.zeta.demo.mq.model.entity.DemoMq2;
import com.zeta.demo.mq.service.IDemoMq2Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.zetaframework.core.utils.JSONUtil;
import org.zetaframework.mq.utils.MessageUtil;

import java.util.function.Consumer;

/**
 * Mq消息消费者
 *
 * @author gcc
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class Demo2Consumer {

    private final IDemoMq2Service service;

    /**
     * demo创建事件 消费者
     */
    @Bean
    public Consumer<Message<DemoDTO>> demoCreateConsumer() {
        return msg -> {
            log.info("接收到demo创建事件消息：{}", JSONUtil.toJsonStr(msg.getPayload()));

            // 处理消息
            MessageUtil.handleMessage("demo创建事件", msg, () -> {
                // 转换成DemoMq2实体类
                DemoMq2 entity = BeanUtil.toBean(msg.getPayload(), DemoMq2.class);
                service.save(entity);
            });
        };
    }

    /**
     * demo修改事件 消费者
     */
    @Bean
    public Consumer<Message<DemoDTO>> demoUpdateConsumer() {
        return msg -> {
            log.info("接收到demo修改事件消息：{}", JSONUtil.toJsonStr(msg.getPayload()));

            // 处理消息
            MessageUtil.handleMessage("demo修改事件", msg, () -> {
                // 转换成DemoMq2实体类
                DemoMq2 entity = BeanUtil.toBean(msg.getPayload(), DemoMq2.class);
                service.updateById(entity);
            });
        };
    }

}
